import { ApiLogin } from "../../api/api.login";
import { ApiVerifyPalm } from "../../api/api.plam";
import { StorageTokenKey, StorageUserKey } from "../../utils/config";
import { ApiLoginReqInterface, ApiLoginResInterface } from "../../interface/api.login.interface";
import { UnionidInterface, ResInterface } from "../../interface/request.interface";
import { AsyncShowToast, CheckSession, GetAppId, GetLocal, Login, SetLocal, ToPage } from "../../utils/common";

Page({
  // 页面的初始数据
  data: {
    // 是否已经分析
    analyzed: false,
  },

  // 生命周期函数--监听页面加载
  async onLoad() {
    try {
      // 用户信息
      const _CheckSession: boolean = await CheckSession();
      console.log('_CheckSession', _CheckSession)
      if (_CheckSession) {
        const _GetLocal = await GetLocal(StorageTokenKey);
        if (!_GetLocal['token']) {
          await this.login();
        }
      } else {
        await this.login();
      }
      // 是否已经分析过
      const _verifyDivince = await this.verifyDivince();
      this.setData({
        isDivince: _verifyDivince
      });
    } catch (error) {
      await AsyncShowToast(error);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 登录
  async login(): Promise<boolean> {
    try {
      const _Login: string = await Login();
      console.log('客户端获取的', _Login);
      const _GetAppId: string = await GetAppId();
      console.log('AppId', _GetAppId)
      const _data: ApiLoginReqInterface = {
        app_id: _GetAppId,
        code: _Login,
      };
      console.log('登录参数', _data)
      const _ApiLogin: ResInterface = await ApiLogin({
        data: _data
      });
      console.log('登录返回值', _ApiLogin)
      const { code, data, message } = _ApiLogin;
      if (code === 200) {
        const _data: ApiLoginResInterface = {
          token: data['token'] || '',
        };
        await SetLocal(StorageTokenKey, _data);
        return true;
      } else {
        throw message || '登录接口请求失败';
      }
    } catch (error) {
      console.log('error', error)
      throw error;
    }
  },
  // 是否已验证过手相
  async verifyDivince() {
    try {
      const _ApiVerifyPalm: ResInterface = await ApiVerifyPalm();
      const { code, data } = _ApiVerifyPalm;
      if (code === 200) {
        return data;
      } else {
        return false;
      }
    } catch (error) {
      throw error;
    }
  },
  // 跳转按钮事件
  async onActive(): Promise<any> {
    try {
      if (this.data.analyzed) {
        await ToPage('/pages/palm.detail/palm.detail');
      } else {
        await ToPage('/pages/palm.upload/palm.upload');
      }
    } catch (error) {
      await AsyncShowToast(error);
    }
  },
})